import random
import types
from copy import copy
import pickle

def generateRandomExpr(fs, ts, maxd=5, method='full'):
    if (maxd == 0 or (method == 'grow' and random.random() < 0.5)):
        expr = random.choice(ts)
    else:
        func = random.choice(fs)
        arg1 = generateRandomExpr(fs, ts, maxd-1, method)
        arg2 = generateRandomExpr(fs, ts, maxd-1, method)
        expr = [func,arg1,arg2]
    return expr

def evalTree(tree, ds):
    if type(tree) == types.ListType:
        if tree[0] == '+':
            return evalTree(tree[1], ds) + evalTree(tree[2], ds)
        elif tree[0] == '-':
            return evalTree(tree[1], ds) - evalTree(tree[2], ds)
        elif tree[0] == '*':
            return evalTree(tree[1], ds) * evalTree(tree[2], ds)
        elif tree[0] == '%':
            arg2 = evalTree(tree[2], ds)
            if arg2 != 0:
                return evalTree(tree[1], ds) / arg2
            return 1
    elif type(tree) == types.TupleType:
        if tree[0] == 'h':
            idx = ds.__len__()-1-tree[1]
            return float(ds[idx])
        else:
            print "err"
            return 4711
    elif type(tree) == types.FloatType or type(tree) == types.IntType:
        return float(tree)
    else:
        print "unknown tree element"
        
def genFibo(num):
    fibo = [1,1]
    for i in range(num-2):
        fibo.append(fibo[i]+fibo[i+1])
        
    return fibo


fs = ['+','-','%']
ts = [0.1,0.2,('h',0),('h',10),('h',20),('h',30),('h',40),('h',50)]
        

#abbn = open('abbn.txt')
#for LAST in abbn.readlines():
#    ds.append(float(LAST))

seed = ones(100)

##gp2 = ['+',('h',0),('h',1)]
##ds = genFibo(10)
##gp = ['+', ['+', ['%', ('h', 0), 2], ['-', 2, 2]], ['*', ['-', ('h', 0), ('h', 5)], ['%', 1, ('h', 1)]]]

fig = figure('graph')

for indi_no in range(100):
    gp = generateRandomExpr(fs, ts, 5, 'full')
    dsfuture = copy(seed[:-10])
        
    for i in range(200):
        r = evalTree(gp, dsfuture)
        dsfuture = append(dsfuture, r)   
        
    if max(dsfuture)-min(dsfuture) < 100000:
        print gp
        
        f = open('result/tree_'+str(indi_no)+'.pkl','w')
        pickle.dump(gp,f)
        f.close()

        f = open('result/series_'+str(indi_no)+'.txt','w')
        for num in dsfuture:
            f.write(str(num)+'\n')
        f.close()

        clf()
        plot(dsfuture,'r')
        fig.savefig('result/graph_'+str(indi_no)+'.png')

